<script lang="ts" setup>
import type { FormInstance } from 'ant-design-vue';

import { onMounted, reactive, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { DICT_TYPE, dictUtils } from '#/utils/dict';

import EditProvinceForm from './edit-province-form.vue';

const emit = defineEmits(['success']);

export interface EditProvinceModalState {
  isUpdate: boolean;
  record: any;
}

const data = ref<EditProvinceModalState>({
  isUpdate: false,
  record: {},
});

const dictMap = reactive<any>({});

let form = reactive({
  type: '',
  name: '',
  value: '',
  status: 0,
  sort: 0,
  isDefault: false,
  extend1: '',
  extend2: '',
  colorType: '',
  customStyle: '',
  remark: '',
});

const formRef = ref<FormInstance>();

const isLoading = ref(false);

const [BaseModal, baseModalApi] = useVbenModal({
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      data.value = baseModalApi.getData<EditProvinceModalState>();
      form = data.value.record;
    }
  },
  onConfirm: onSubmit,
});

async function onSubmit() {
  await formRef.value!.validate();

  try {
    isLoading.value = true;

    message.success({
      content: `操作成功`,
    });

    baseModalApi.close();
    emit('success');
  } catch (error) {
    console.error('表单验证失败:', error);
  } finally {
    isLoading.value = false;
  }
}

onMounted(async () => {
  dictMap.value = await dictUtils.getDictDatasAsync([
    { type: DICT_TYPE.sysCommonStatus, valueType: 'number' },
    { type: DICT_TYPE.sysCommonWhether, valueType: 'number' },
    { type: DICT_TYPE.sysCommonColorType, valueType: 'string' },
  ]);
});
</script>
<template>
  <BaseModal
    :confirm-loading="isLoading"
    :title="data.isUpdate ? '修改字典数据' : '新增字典数据'"
    class="w-[600px]"
  >
    <EditProvinceForm v-model:form="form" type="modal" />
  </BaseModal>
</template>
